package com.imti.retrofitweatherdemo;

import static java.nio.charset.StandardCharsets.UTF_8;

import android.app.Application;
import android.util.Log;
import com.imti.retrofitweatherdemo.logic.NewsLogic;
import com.imti.retrofitweatherdemo.net.hospital.HospitalRequest;
import com.imti.retrofitweatherdemo.net.news.NewsRequest;
import com.imti.retrofitweatherdemo.net.weather.WeatherRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.logging.HttpLoggingInterceptor.Level;
import okhttp3.logging.HttpLoggingInterceptor.Logger;
import okio.Buffer;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class BaseApplication extends Application
{

    public WeatherRequest weatherRequest;

    public NewsRequest newsRequest;

    public HospitalRequest hospitalRequest;

    private Retrofit mRetrofit;

    //新闻
    private Retrofit mNewsRetrofit;

    private Retrofit mHospitalRetrofit;

    @Override
    public void onCreate()
    {
        super.onCreate();

        initWeatherRetrofit();
        weatherRequest = mRetrofit.create(WeatherRequest.class);
        //新闻
        newsRequest = mNewsRetrofit.create(NewsRequest.class);

        hospitalRequest = mHospitalRetrofit.create(HospitalRequest.class);
    }

    private void initWeatherRetrofit()
    {
        //retrofit的Log日志拦截器
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new Logger()
        {
            @Override
            public void log(String message)
            {
                try
                {
                    URLEncoder.encode(message, "utf-8");
                } catch (UnsupportedEncodingException e)
                {
                    e.printStackTrace();
                }
            }
        });
        interceptor.setLevel(Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                                  //设置连接超时时间
                                  .callTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                                  //设置读取超时时间
                                  .readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
//                                  .addInterceptor(interceptor)
                                  .addInterceptor(new Interceptor()
                                  {

                                      @Override
                                      public Response intercept(Chain chain) throws IOException
                                      {
                                          Request request = chain.request();
                                          long startTime = System.currentTimeMillis();
                                          okhttp3.Response response = chain
                                                                          .proceed(chain.request());
                                          long endTime = System.currentTimeMillis();
                                          long duration = endTime - startTime;
                                          okhttp3.MediaType mediaType = response.body()
                                                                            .contentType();
                                          String content = response.body().string();

                                          Log.e("请求地址", "intercept: " + request.toString());
                                          Log.e("返回数据", "intercept: " + content);
                                          Log.e("数据格式", "intercept: " + mediaType);
                                          printParams(request.body());
                                          Log.e("时间",
                                              "----------请求耗时:" + duration + "毫秒----------");
                                          return response.newBuilder().body(
                                              okhttp3.ResponseBody.create(mediaType, content))
                                                     .build();
                                      }
                                  })
                                  .build();

        mRetrofit = new Retrofit.Builder()
                        .client(client)
                        .baseUrl(BuildConfig.WEATHER_HOST)
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();

        mNewsRetrofit = new Retrofit.Builder()
                            .client(client)
                            .baseUrl(BuildConfig.NEWS_HOST)
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();

        mHospitalRetrofit = new Retrofit.Builder()
                                .client(client)
                                .baseUrl(BuildConfig.HOSPITAL_HOST)
                                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                                .addConverterFactory(GsonConverterFactory.create())
                                .build();
    }

    private void printParams(RequestBody body)
    {
        Buffer buffer = new Buffer();
        try
        {
            if (null != body)
            {
                body.writeTo(buffer);
                Charset charset = Charset.forName("UTF-8");
                MediaType contentType = body.contentType();
                if (contentType != null)
                {
                    charset = contentType.charset(UTF_8);
                }
                String params = buffer.readString(charset);
                Log.e("请求参数", "printParams: " + params);
            }

        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public WeatherRequest getWeatherRequest()
    {
        return weatherRequest;
    }

    //新闻
    public NewsRequest getNewsRequest()
    {
        return newsRequest;
    }
}
